<?php

/**
 * Created by PhpStorm.
 * User: KeenSting
 * Date: 2017/11/22
 * Time: 下午2:09
 * Name: 梁小苍
 * Phone: 13126734215
 * QQ: 707719848
 * File Description: 国密算法SM4 对称加密
 */
class Lib_MediationApi_Curl
{
    public static function postjson($url, $params = [], $timeout = 30, $ssl_data = array())
    {
        $json_header = array('Content-Type:application/json;charset=utf-8');


        $params = json_encode($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $json_header);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        if (!empty($ssl_data)) {
            //服务端CA 存放路径
            curl_setopt($ch, CURLOPT_CAINFO, $ssl_data['caPath']);
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            //证书目录地址
            curl_setopt($ch, CURLOPT_SSLCERT, $ssl_data['clientCrtPath']);
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            //私钥路径
            curl_setopt($ch, CURLOPT_SSLKEY, $ssl_data['privateKeyPath']);
        }
        $log = array();
        $res = curl_exec($ch);
        $log['errno'] = curl_errno($ch);
        $log['error'] = curl_error($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['error'] = $log['errno'];
            return $result;
        }
        curl_close($ch);
        $res = json_decode(substr($res, $header_size), true);
        if (!is_array($res) || count($res) <= 0) {
            //返回值错误日志
            $result['error'] = $log['errno'];
            return $result;
        }
        $res['error'] = 200;
        return $res;
    }

}
